package 二叉树.反转二叉树;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/1/30 13:29
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2,new TreeNode(1),new TreeNode(3));
        root.right = new TreeNode(7,new TreeNode(6),new TreeNode(9));
        System.out.println(invertTree(root).left.val);
    }

    //利用BFS 整棵树的反转其实就是每个节点的左右节点反转
    public static TreeNode invertTree(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null){
            return null;
        }
        queue.offer(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            while (size > 0){
                TreeNode node = queue.poll();
                if (node.left != null){
                    queue.offer(node.left);
                }
                if (node.right != null){
                    queue.offer(node.right);
                }
                TreeNode tempNode = new TreeNode();
                tempNode = node.left;
                node.left = node.right;
                node.right = tempNode;
                size--;
            }
        }
        return root;
    }


    //递归
    public static TreeNode invertTree2(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);
        root.left = right;
        root.right = left;
        return root;
    }

}
